package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ghy.constant.ML;
import com.ghy.dto.SeasonInsertDTO;
import com.ghy.dto.SeasonPageDTO;
import com.ghy.dto.SeasonUpdateDTO;
import com.ghy.entity.Course;
import com.ghy.exception.ServiceException;
import com.ghy.mapper.CourseMapper;
import com.ghy.mapper.EpisodeMapper;
import com.ghy.vo.SeasonSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.entity.Season;
import com.ghy.mapper.SeasonMapper;
import com.ghy.service.SeasonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.ghy.entity.table.CourseTableDef.COURSE;
import static com.ghy.entity.table.EpisodeTableDef.EPISODE;
import static com.ghy.entity.table.SeasonTableDef.SEASON;

/**
 * 季次表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "season")
public class SeasonServiceImpl extends ServiceImpl<SeasonMapper, Season>  implements SeasonService{

    @Autowired
    private SeasonService seasonService;

    @Autowired
    private EpisodeMapper episodeMapper;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeasonInsertDTO dto) {
        //标题查重
        if (QueryChain.of(mapper)
                .where(SEASON. TITLE.eq(dto.getTitle()))
                .exists()) {
            throw new ServiceException("谋程标题已存在");
        }

        //组装entity实体类
        Season season = BeanUtil.copyProperties(dto, Season.class);
        season.setCreated(LocalDateTime.now());
        season.setUpdated(LocalDateTime.now());

        return mapper.insert(season) > 0;
    }

    @Cacheable(key = "#p0",
            condition = "#p0 != null ",
            unless = " #result == null")
    @Override
    public Season select(Long id) {
        RelationManager.addQueryRelations("category", "seasons","episodes");
        return mapper. selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition="#p0 != null",
            unless = "#result == null")
    @Override
    public List<SeasonSimpleListVO> simpleList(){
        //RelationManager.addQueryRelations("category", "seasons","episodes");

        return QueryChain.of(mapper)
                .withRelations()
                .listAs(SeasonSimpleListVO.class);
    }

    @Override
    public Page<Season> page(SeasonPageDTO dto) {
        //RelationManager.addQueryRelations("category", "seasons","episodes");
        QueryChain<Season> queryChain = QueryChain.of(mapper)
                .orderBy(SEASON. IDX .asc(), SEASON.ID.desc());

        // title 条件
        String title = dto.getTitle();
        if (ObjectUtil.isNotNull(title)) {
            queryChain.where(SEASON.TITLE.like(title));
        }

        // courseId 条件
        Long courseId = dto.getFkCourseId();
        if (ObjectUtil.isNotNull(courseId)) {
            queryChain .where(SEASON.FK_COURSE_ID.eq(courseId)) ;
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));

    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeasonUpdateDTO dto) {
        //标题查重
        if (QueryChain.of(mapper)
                .where(SEASON. TITLE.eq(dto. getTitle()))
                .and (SEASON. ID.ne(dto .getId()))
                .exists()) {
            throw new ServiceException("某集次标题已存在");
        }

        //组装entity 实体类
        Season season = BeanUtil.copyProperties(dto, Season.class);
        season.setUpdated( LocalDateTime.now());

        return UpdateChain.of(season)
                .where(SEASON.ID.eq(season.getId()) )
                .update();

    }

    @Transactional(rollbackFor = Exception. class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        //通过课程主键查询全部季次的ID列表
        // select id from season where fk_course_id = ?
        List<Long> episodeIds = QueryChain.of(episodeMapper)
                .select(EPISODE.ID)
                .where(EPISODE. FK_SEASON_ID.eq(id))
                .objListAs(Long. class);
        //存在季记录时，批量别除季
        this.clearSeasonAndEpisode(episodeIds) ;

        //制除课程
        return mapper.deleteById(id) > 0;
    }


    @Transactional(rollbackFor = Exception. class)
    @CacheEvict(allEntries = true)
    public boolean deleteBatch(List<Long> ids) {

        // select id from episode where fk_season_id in (?)
        List<Long> episodeIds = QueryChain.of(episodeMapper)
                .select(EPISODE.ID)
                .where(EPISODE. FK_SEASON_ID.in(ids ))
                .objListAs(Long. class);

        //存在季记录时，批量别除季
        this .clearSeasonAndEpisode(episodeIds) ;

        //批量划除课程
        return mapper.deleteBatchByIds(ids) > 0;
    }

    private void clearSeasonAndEpisode(List<Long> episodeIds) {
        if (ObjectUtil.isNotEmpty(episodeIds)) {
            if (episodeMapper.deleteBatchByIds(episodeIds) <= 0) {
                throw new ServiceException("季次删除失败");
            }
        }
    }
}
